import { Effect, Reducer, Subscription } from 'umi';
import { dataApi } from '@/utils/api';

export interface IndexModelState {
  name: string;
  grades: any[];
}

export interface IndexModelType {
  // 当我们的字符串常量，可以直接拿这个字符串作为数据类型
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
    load: Effect;
  };
  reducers: {
    save: Reducer;
    change: Reducer;
    getData: Reducer;
  };
  subscriptions: { setup: Subscription };
}

// IndexModel就是仓库实例
const IndexModel: IndexModelType = {
  // 命名空间
  namespace: 'index',

  // 仓库数据
  state: {
    name: 'zhangsan',
    grades: [],
  },

  // 异步方法，在这个里面调用reducers，不能直接修改数据
  effects: {
    *query({ payload }, { call, put }) {},
    *load({ payload }, { call, put }) {
      const res = yield call(dataApi);
      yield put({ type: 'getData', payload: res.result });
    },
  },

  // 同步方法，用来改变state的
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    change(state, action) {
      return {
        ...state,
        name: action.name,
      };
    },
    getData(state, action) {
      return {
        ...state,
        grades: action.payload,
      };
    },
  },

  // 可以用来做url监听
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        // console.log(pathname);
        if (pathname === '/dva') {
          dispatch({
            type: 'load',
          });
        }
      });
    },
  },
};

export default IndexModel;
